package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.mapper.ProductMapper;
import com.zhentao.pojo.Product;
import com.zhentao.service.CartService;
import com.zhentao.vo.CartItemVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class CartServiceImpl implements CartService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ProductMapper productMapper;
    private static final String CART_PREFIX = "cart:";//购物车前缀
    private static final long CART_EXPIRE_DAYS = 7;

    @Override
    public void addToCart(Long userId, Long productId, Integer quantity) {
        // 1. 校验商品
        Product product = checkAndGetProduct(productId);

        // 2. 获取用户购物车
        String cartKey = CART_PREFIX + userId;
        Map<Object, Object> cartItems = redisTemplate.opsForHash().entries(cartKey);//获取购物车项

        // 3. 更新购物车
        Integer currentQuantity = (Integer) cartItems.getOrDefault(productId.toString(), 0);//获取当前商品数量
        if (currentQuantity + quantity > product.getStock()) {//超出库存
            throw new RuntimeException("商品库存不足");
        }
        redisTemplate.opsForHash().put(cartKey, productId.toString(), currentQuantity + quantity);
        redisTemplate.expire(cartKey, CART_EXPIRE_DAYS, TimeUnit.DAYS);
    }

    @Override
    public List<CartItemVO> getCartItems(Long userId) {
        // 1. 获取用户购物车
        String cartKey = CART_PREFIX + userId;
        Map<Object, Object> cartItems = redisTemplate.opsForHash().entries(cartKey);

        // 2. 转换为VO列表
        List<CartItemVO> cartItemVOs = new ArrayList<>();
        for (Map.Entry<Object, Object> entry : cartItems.entrySet()) {
            Long productId = Long.valueOf(entry.getKey().toString());
            Integer count = (Integer) entry.getValue();

            Product product = productMapper.selectById(productId);
            if (product != null && product.getIsDeleted() == 1 && product.getStatus() == 1) {
                CartItemVO cartItemVO = new CartItemVO();
                cartItemVO.setProductId(productId);
                cartItemVO.setName(product.getName());
                cartItemVO.setImage(product.getImage());
                cartItemVO.setPrice(product.getPrice());
                cartItemVO.setCount(count);
                cartItemVO.setStatus(product.getStatus());
                cartItemVOs.add(cartItemVO);
            }
        }
        return cartItemVOs;
    }

    @Override
    public void removeFromCart(Long userId, Long productId) {
        String cartKey = CART_PREFIX + userId;
        redisTemplate.opsForHash().delete(cartKey, productId.toString());
    }

    @Override
    public void updateCartItemQuantity(Long userId, Long productId, Integer quantity) {
        // 1. 校验商品
        Product product = checkAndGetProduct(productId);
        if (quantity > product.getStock()) {
            throw new RuntimeException("商品库存不足");
        }

        // 2. 更新购物车
        String cartKey = CART_PREFIX + userId;
        if (quantity <= 0) {
            redisTemplate.opsForHash().delete(cartKey, productId.toString());
        } else {
            redisTemplate.opsForHash().put(cartKey, productId.toString(), quantity);
        }
    }

    @Override
    public void clearCart(Long userId) {
        String cartKey = CART_PREFIX + userId;
        redisTemplate.delete(cartKey);
    }

    private Product checkAndGetProduct(Long productId) {
        Product product = productMapper.selectById(productId);
        if (product == null || product.getIsDeleted() == 0) {
            throw new RuntimeException("商品不存在");
        }
        if (product.getStatus() == 0) {
            throw new RuntimeException("商品已下架");
        }
        return product;
    }
}
